package com.ityj.cmn.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ityj.cmn.mapper.DictMapper;
import com.ityj.cmn.service.DictService;
import com.ityj.yygh.model.cmn.Dict;
import org.apache.commons.lang3.StringUtils;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class DictServiceImpl extends ServiceImpl<DictMapper, Dict> implements DictService {

    @Override
    @Cacheable(value = "dict", keyGenerator = "keyGenerator")
    public List<Dict> getChildDataById(Long id) {
        QueryWrapper<Dict> wrapper = new QueryWrapper<>();
        wrapper.eq("parent_id", id);
        List<Dict> dictList = baseMapper.selectList(wrapper);
        dictList.forEach(this::fillHasChild);
        return dictList;
    }

    private void fillHasChild(Dict dict) {
        QueryWrapper<Dict> wrapper = new QueryWrapper<>();
        wrapper.eq("parent_id", dict.getId());
        Integer selectCount = baseMapper.selectCount(wrapper);
        dict.setHasChildren(selectCount > 0);
    }

    /**
     * 修改操作时，需要@CacheEvict 注解
     * allEntries = true: 方法调用后清空所有缓存
     */
    @CacheEvict(value = "dict", allEntries=true)
    public void updateData() {
    }

    @Override
    public String getDictName(String value, String dictCode) {
        Long parentId = null;
        if (StringUtils.isNotEmpty(dictCode)) {
            parentId = getParentId(dictCode);
        }

        QueryWrapper<Dict> wrapper = new QueryWrapper<>();
        if (parentId != null) {
            wrapper.eq("parent_id", parentId);
        }
        wrapper.eq("value", value);
        Dict dict = baseMapper.selectOne(wrapper);
        return dict.getName();
    }

    public Long getParentId(String dicCode) {
        QueryWrapper<Dict> wrapper = new QueryWrapper<>();
        wrapper.eq("dict_code", dicCode);
        Dict dict = baseMapper.selectOne(wrapper);
        return dict.getId();
    }

    @Override
    public List<Dict> getDictByDictCode(String dictCode) {
        // 根据dictCode 获取出字列表的ID
        Long parentId = this.getParentId(dictCode);
        // 根据ID查出对应的Dict
        return this.getChildDataById(parentId);
    }

}
